package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.client.article.IArticleClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.article.ApArticle;
import com.heima.model.common.vo.wemedia.NewsDimensionVo;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author: fly
 * @date: 2024-08-02 14:18
 */
@Service
public class StatisticsServiceImpl implements StatisticsService {
    @Autowired
    private IArticleClient articleClient;

    /**
     * 图文数据总览
     * @param beginDate
     * @param endDate
     * @return
     */
    @Override
    public ResponseResult newsDimension(Date beginDate, Date endDate) {
        ResponseResult res = newsPage(beginDate, endDate, 1, 1000);
        List<ApArticle> listAll = JSON.parseArray(JSON.toJSONString(res.getData()), ApArticle.class);
        int likesNum = 0;
        int collectNum = 0;
        for (ApArticle article : listAll) {
            if (article.getLikes() != null && article.getCollection() != null){
                likesNum += article.getLikes();
                collectNum += article.getCollection();
            }
        }
        NewsDimensionVo vo = NewsDimensionVo.builder()
                .likesNum(likesNum)
                .collectNum(collectNum)
                .publishNum(listAll.size()).build();
        return PageResponseResult.okResult(vo);
    }

    /**
     * 图文数据列表
     * @param beginDate
     * @param endDate
     * @param page
     * @param size
     * @return
     */
    @Override
    public ResponseResult newsPage(Date beginDate, Date endDate, Integer page, Integer size) {
        Integer id = WmThreadLocalUtil.get();
        PageResponseResult res = articleClient.newsPage(beginDate, endDate, page, size,id);
        if (res.getCode() == 200){
            return JSON.parseObject(JSON.toJSONString(res), PageResponseResult.class);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }
}
